package com.yylc.cscore.controller;

import cn.hutool.core.util.StrUtil;
import com.yylc.cscore.bean.TaskRuleBean;
import com.yylc.cscore.component.JobScheduler;
import com.yylc.cscore.service.TaskRuleService;
import com.yylc.cscore.util.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author xiangnan
 * date 2018/5/2
 */
@RequestMapping("/rule")
@RestController
public class TaskRuleController {

    @Resource
    private TaskRuleService taskRuleService;

    @Resource
    private JobScheduler jobScheduler;

    @PostMapping("/page/list")
    public Object getConsumerPageList(@RequestParam int type, @RequestParam int current, @RequestParam int size) {
        if (current < 1 || size < 1 || type < 0 || type > 1) {
            throw new RuntimeException("参数错误");
        }

        return taskRuleService.getTaskRuleList(type, current, size);
    }

    @PostMapping
    public Object addTaskRule(TaskRuleBean bean) {
        if (bean == null || !bean.valid()) {
            throw new RuntimeException("参数错误");
        }

        return taskRuleService.addTaskRule(bean);
    }

    @PutMapping("/artificial/trigger")
    public Object artificialTriggerTaskRule(TaskRuleBean bean, @RequestParam String userIdList) {
        if (bean == null || StrUtil.isBlank(bean.getAllotServiceId()) || StrUtil.isBlank(bean.getAllotTaskCode()) ||
                bean.getAllotment() <= 0) {
            throw new RuntimeException("参数错误");
        }

        return taskRuleService.artificialTriggerTaskRule(bean, userIdList);
    }

    @PutMapping("/trigger")
    public Object triggerTaskRule(@RequestParam int id) {
        if (id <= 0) {
            throw new RuntimeException("参数错误");
        }

        return taskRuleService.triggerTaskRule(id);
    }

    @PutMapping
    public Object updateTaskRule(TaskRuleBean bean) {
        if (bean == null || !bean.valid()) {
            throw new RuntimeException("参数错误");
        }

        return taskRuleService.updateTaskRule(bean);
    }

    @PutMapping("/status/{status}/{id}")
    public Object updateTaskRule(@PathVariable int status, @PathVariable int id) {
        if (status != R.taskRuleStatus.INIT && status != R.taskRuleStatus.RUNNING) {
            throw new RuntimeException("页数错误");
        }

        return taskRuleService.updateTaskRule(status, id);
    }

    @PutMapping("/delete")
    public Object deleteCustomer(TaskRuleBean bean) {
        if (bean == null || !bean.valid()) {
            throw new RuntimeException("参数错误");
        }

        return taskRuleService.deleteTaskRule(bean);
    }

    @PutMapping("/check/cron")
    public Object deleteCustomer(@RequestParam String cron) {
        if (StrUtil.isBlank(cron)) {
            throw new RuntimeException("参数错误");
        }

        return jobScheduler.checkCron(cron);
    }

}
